package com.service.schedule.util;

import com.common.DateUtils;
import com.model.schedule.JobLogModel;
import com.model.schedule.JobModel;
import com.model.schedule.ScheduleJob;
import com.service.schedule.JobLogService;
import com.service.schedule.JobService;
import com.service.schedule.ScheduleJobLogService;

import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class QuartzJob extends QuartzJobBean {

	static final Logger logger = LoggerFactory.getLogger(QuartzJob.class);

	private ExecutorService service = Executors.newSingleThreadExecutor();

	protected void executeInternal(JobExecutionContext context) {

		JobModel scheduleJob = (JobModel) context.getMergedJobDataMap().get(ScheduleJob.JOB_PARAM_KEY);

		// 获取spring bean
		JobLogService scheduleJobLogService = (JobLogService) SpringContextUtils.getBean("jobLogService");
		JobService scheduleJobService = (JobService) SpringContextUtils.getBean("jobService");
		if (scheduleJobLogService.getActive().equals("prod")) {
//			return;
		}

		// 数据库保存执行记录
		JobLogModel scheduleJobLog = new JobLogModel();
//		scheduleJobLog.setId(UUID.randomUUID().toString());
		scheduleJobLog.setJobId(scheduleJob.getJobId());
		scheduleJobLog.setBeanName(scheduleJob.getBeanName());
		scheduleJobLog.setMethodName(scheduleJob.getMethodName());
		scheduleJobLog.setParams(scheduleJob.getParams());
		scheduleJobLog.setBeginTime(com.common.DateUtils.getCurrentTime());

		// 如果是正在执行的状态，则不再执行
//		JobModel scheduleJobResult = (JobModel) scheduleJobService.selectInfor(scheduleJob.getJobId()).getData();
//		if (scheduleJobResult == null || (Constant.SCHEDULE_RUN_STATUS_RUN == scheduleJobResult.getRunStatus())) {
//			return;
//		}
		// 任务执行中
		long startTime = System.currentTimeMillis();
//		scheduleJobResult.setBeginTime(com.common.DateUtils.getCurrentTime());
//		scheduleJobResult.setErrorLog(null);
//		scheduleJobResult.setRunStatus(Constant.SCHEDULE_RUN_STATUS_RUN);
//		scheduleJobResult.setEndTime(null);
//		scheduleJobService.save(scheduleJobResult);

		try {
			// 执行任务
			ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getBeanName(), scheduleJob.getMethodName(),
					scheduleJob.getParams());
			Future<?> future = service.submit(task);
			future.get();
			// 任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			scheduleJobLog.setTimes((int) times);
			scheduleJobLog.setEndTime(com.common.DateUtils.getCurrentTime());
			// 执行状态 0：成功 1：失败 2:执行中
			scheduleJobLog.setRunStatus(Constant.SCHEDULE_RUN_STATUS_SUCCESS);

//			scheduleJobResult.setRunStatus(Constant.SCHEDULE_RUN_STATUS_SUCCESS);
//			scheduleJobResult.setEndTime(com.common.DateUtils.getCurrentTime());

		} catch (Exception e) {
			// 任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			scheduleJobLog.setTimes((int) times);
			scheduleJobLog.setEndTime(DateUtils.getCurrentTime());
			// 执行状态 0：成功 1：失败 2：执行中
			scheduleJobLog.setRunStatus(Constant.SCHEDULE_RUN_STATUS_FAIL);
			scheduleJobLog.setErrorLog(e.getMessage());

//			scheduleJobResult.setRunStatus(Constant.SCHEDULE_RUN_STATUS_FAIL);
//			scheduleJobResult.setEndTime(DateUtils.getCurrentTime());
//			scheduleJobResult.setErrorLog(e.getMessage());
			logger.error(e.getMessage());
		} finally {
			scheduleJobLogService.save(scheduleJobLog);
//			scheduleJobService.save(scheduleJobResult);
		}
	}

	/**
	 * 发送短信
	 *
	 * @param scheduleJobName 定时任务名称
	 */
	private void pushSms(String scheduleJobName) {
//		if (scheduleJobName.length() > 20) {
//			scheduleJobName = scheduleJobName.substring(0, 20);
//		}
//		RabbitTemplate rabbitTemplate = (RabbitTemplate) SpringContextUtils.getBean("rabbitTemplate");
//		ObjectMapper objectMapper = new ObjectMapper();
//		TelephonesConfig telephonesConfig = (TelephonesConfig) SpringContextUtils.getBean("telephonesConfig");
//		String[] telephones = telephonesConfig.getPhones();
//		Map<String, Object> map = new HashMap<>(2);
//		map.put("date", DateUtils.getCurrentTime(DateUtils.DATE_PATTERN));
//		map.put("scheduleJobName", scheduleJobName);
//		for (String telephone : telephones) {
//			WphSms wphSms = new WphSms();
//			wphSms.setTemplateCode(TemplateCodeEnum.SCHEDULE_JOB);
//			wphSms.setCreateBy("sd-ylsw");
//			wphSms.setParams(map);
//			wphSms.setTelephone(telephone);
//			PushMessage.pushMsg(rabbitTemplate, objectMapper, MessageQueueEnum.wphSmsQueue, wphSms);
//		}
	}
}
